package com.qdxwx.common.utils;

import org.apache.commons.codec.digest.DigestUtils;

import jakarta.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 文件处理工具类
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
public class FileUtils {
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8);
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8);
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8);
        }
        return filename;
    }

    //拷贝文件
    public static boolean copyFile(String fileFrom, String fileTarget) {
        return copyFile(new File(replacePath(fileFrom)), new File(replacePath(fileTarget)));
    }

    public static boolean copyFile(InputStream inputStream, String fileTarget) {
        try {
            FileOutputStream outputStream = new FileOutputStream(replacePath(fileTarget));
            byte[] by = new byte[4096];
            int len;
            while ((len = inputStream.read(by)) != -1) {
                outputStream.write(by, 0, len);
            }
            outputStream.close();
            return true;
        } catch (Exception e) {
            e.getStackTrace();
            return false;
        }
    }

    //拷贝文件
    public static boolean copyFile(File fileFrom, File fileTarget) {
        try {
            if (!fileTarget.getParentFile().exists()) {
                if (!fileTarget.getParentFile().mkdirs()) {
                    return false;
                }
            }
            FileInputStream inputStream = new FileInputStream(fileFrom);
            FileOutputStream outputStream = new FileOutputStream(fileTarget);
            byte[] by = new byte[4096];
            int len;
            while ((len = inputStream.read(by)) != -1) {
                outputStream.write(by, 0, len);
            }
            inputStream.close();
            outputStream.close();
            return true;
        } catch (Exception e) {
            e.getStackTrace();
            return false;
        }
    }
    /**
     * 获取SHA256值
     * @param path 文件路径
     * @return
     */
    public static String getSHA256(String path) {
        try {
            return DigestUtils.sha256Hex(new FileInputStream(path));
        } catch (Exception ex) {
            return null;
        }
    }
    /**
     * 获取SHA256值
     * @param inputStream
     * @return
     */
    public static String getSHA256(InputStream inputStream) {
        try {
            return DigestUtils.sha256Hex(inputStream);
        } catch (Exception ex) {
            return null;
        }
    }
    /**
     * 获取md5值
     * @param path 文件路径
     * @return
     */
    public static String getMD5(String path) {
        try {
            return DigestUtils.md5Hex(new FileInputStream(path));
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 获取md5值
     * @param inputStream
     * @return
     */
    public static String getMD5(InputStream inputStream) {
        try {
            return DigestUtils.md5Hex(inputStream);
        } catch (Exception ex) {
            return null;
        }
    }

    public static String replacePath(String path) {
        return path.replace("/", "\\");
    }
}
